package com.atguigu.realtime.gmallpublisher.controller;

import com.alibaba.fastjson.JSON;
import com.atguigu.realtime.gmallpublisher.service.PublisherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author lzc
 * @Date 2020/11/14 10:25
 */
@RestController
public class PublisherController {

    @Autowired
    private PublisherService service;

    @GetMapping("/realtime-total")
    public String realtimeTotal(String date) throws IOException {
        Long dau = service.getDau(date);

        ArrayList<Map<String, Object>> result = new ArrayList<>();

        // 添加两个map集合
        HashMap<String, Object> map1 = new HashMap<>();
        map1.put("id", "dau");
        map1.put("name", "新增日活");
        map1.put("value", dau);
        result.add(map1);

        HashMap<String, Object> map2 = new HashMap<>();
        map2.put("id", "new_mid");
        map2.put("name", "新增设备");
        map2.put("value", 233);
        result.add(map2);


        HashMap<String, Object> map3 = new HashMap<>();
        map3.put("id", "order_amount");
        map3.put("name", "新增交易额");
        map3.put("value", service.getOrderAmount(date));
        result.add(map3);
        System.out.println(result);

        return JSON.toJSONString(result);
    }

    @GetMapping("/realtime-hour")
    public String realtimeHour(String id, String date) throws IOException {
        if ("dau".equals(id)) {
            Map<String, Long> today = service.getHourDau(date);
            Map<String, Long> yesterday = service.getHourDau(getYesterday(date));

            Map<String, Map<String, Long>> result = new HashMap<>();
            result.put("today", today);
            result.put("yesterday", yesterday);

            return JSON.toJSONString(result);
        } else if("order_amount".equals(id)){   // http://localhost:8070/realtime-hour?id=order_amount&date=2020-10-01
            Map<String, BigDecimal>  today = service.getHourOrderAmount(date);
            Map<String, BigDecimal> yesterday = service.getHourOrderAmount(getYesterday(date));

            Map<String, Map<String, BigDecimal>> result = new HashMap<>();
            result.put("today", today);
            result.put("yesterday", yesterday);

            return JSON.toJSONString(result);

        } else {
            return "";
        }
    }

    public String getYesterday(String date) {
        return LocalDate.parse(date).minusDays(1).toString();
    }
}
